package com.lzp.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 银行转账案例--测试JDBC事务
 */
public class AccountDemo {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstmt1 = null;
        PreparedStatement pstmt2 = null;
        try {
            conn = JDBCUtil.getConnection();
            // 转账操作：账号A余额减100，账户B加100
            String sql1 = "update account_jdbc set balance = balance - ? where id = ?";
            String sql2 = "update account_jdbc set balance = balance + ? where id = ?";
            pstmt1 = conn.prepareStatement(sql1);
            pstmt2 = conn.prepareStatement(sql2);

            pstmt1.setDouble(1, 100);
            pstmt1.setInt(2, 1);
            pstmt2.setDouble(1, 100);
            pstmt2.setInt(2, 2);
            /*开启事务*/
            conn.setAutoCommit(false);
            pstmt1.executeUpdate();
            int i = 1 / 0; // 创造异常
            pstmt2.executeUpdate();
            /*提交事务*/
            conn.commit();
        } catch (SQLException e) {
            try {
                /*回滚事务*/
                if (conn != null) {
                    conn.rollback();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            /*关闭资源*/
            JDBCUtil.close(pstmt1, conn);
            JDBCUtil.close(pstmt2, null);
        }
    }
}
